<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Demo 客户端</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 10px
        }

        #log {
            height: 300px;
            overflow-y: scroll;
            border: 1px solid #ccc;
            margin: 10px 0;
            padding: 5px
        }

        input, button {
            padding: 5px;
            margin: 5px
        }

        #msgInput {
            width: 300px
        }
    </style>
</head>
<body>
<h3>WebSocket Demo（服务端：Spring Boot 2.5.3，路由：/ws/route/{token}）</h3>
<div>
    Token：<input id="tokenInput" value="demo-token-123"/><br/>
    用户ID：<input id="userIdInput" value="user-a"/><br/>
    目标用户ID：<input id="targetUserIdInput" value="user-b"/><br/>
    消息：<input id="msgInput" placeholder="内容"/><br/>
    <button onclick="connect()">连接</button>
    <button onclick="sendBroadcast()">广播</button>
    <button onclick="sendUni()">单播</button>
    <button onclick="sendPing()">Ping</button>
    <button onclick="disconnect()">断开</button>
</div>
<div id="log"></div>

<script>
    let ws = null;
    const log = (msg) => {
        const e = document.createElement("div");
        e.textContent = `[${new Date().toISOString()}] ${msg}`;
        document.getElementById("log").appendChild(e);
        window.scrollTo(0, document.body.scrollHeight);
    };

    function connect() {
        if (ws && ws.readyState === WebSocket.OPEN) {
            log("已连接，无需重复连接");
            return;
        }
        const token = document.getElementById("tokenInput").value.trim();
        const userId = document.getElementById("userIdInput").value.trim();
        if (!token) {
            alert("请输入token");
            return;
        }
        // 使用路由模式：/ws/route/{token}，可附加查询参数传递 userId（服务端从URI路径读取token）
        const url = `ws://localhost:8080/demo/ws/route/${encodeURIComponent(token)}?userId=${encodeURIComponent(userId)}`;
        ws = new WebSocket(url);
        ws.onopen = () => log("连接已打开");
        ws.onmessage = (e) => log("收到: " + e.data);
        ws.onclose = () => log("连接已关闭");
        ws.onerror = (e) => log("发生错误: " + e);
    }

    function send(type, data) {
        if (!ws || ws.readyState !== WebSocket.OPEN) {
            log("未连接");
            return;
        }
        const m = {type, content: data};
        if (type === "uni") m.userId = document.getElementById("targetUserIdInput").value.trim();
        ws.send(JSON.stringify(m));
    }

    function sendBroadcast() {
        send("broadcast", document.getElementById("msgInput").value);
    }

    function sendUni() {
        send("uni", document.getElementById("msgInput").value);
    }

    function sendPing() {
        send("ping", "");
    }

    function disconnect() {
        if (ws) {
            ws.close();
        }
    }
</script>
</body>
</html>